<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "ico_config".
 *
 * @property string $id
 * @property string $allcount
 * @property string $current_count
 * @property string $left_count
 * @property string $created_at
 * @property string $updated_at
 * @property string $unit
 */
class IcoConfig extends \common\models\BaseActiveRecord
{
    public $needRecordChangeTableLog=true;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ico_config';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['created_at', 'updated_at'], 'integer'],
            [['allcount', 'current_count', 'left_count'], 'safe'],
            [['unit'], 'string', 'max' => 10],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'allcount' => '币总量',
            'current_count' => '当前发放量',
            'left_count' => '剩余数量',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'unit' => '单位',
        ];
    }

    /**
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert){
        $this->current_count = (string)$this->current_count;
        $this->left_count = (string)$this->left_count;
        return parent::beforeSave($insert);
    }

    /**
     * 总币减少
     * @param $count
     * @return bool
     */
    public function reduce($count)
    {
        if($count>$this->left_count){
            return false;
        }
        $this->current_count += $count;
        $this->left_count = $this->allcount - $this->current_count;
        $this->save();
        return true;
    }

    /**
     * 总币增加
     * @param $count
     * @return bool
     */
    public function increment($count)
    {
        if($count>$this->left_count){
            return false;
        }
        $this->current_count -= $count;
        $this->left_count = $this->allcount - $this->current_count;
        $this->save();
        return true;
    }
}
